﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ReAnimation.Infrastructure.Services.DomainFactories.Interfaces;
using ReAnimation.Domain;
using Castle.DynamicProxy;
using ReAnimation.Helpers.DynamicProxy;
using GLWrap;

namespace ReAnimation.Infrastructure.Services.DomainFactories
{
    public class AnimationFactory: IAnimationFactory
    {
        private static ProxyGenerator _proxyGenerator = new ProxyGenerator();
        private IMoleculeFactory _moleculeFactory;

        public AnimationFactory(IMoleculeFactory moleculeFactory)
        {
            _moleculeFactory = moleculeFactory;
        }

        #region IAnimationFactory Members

        public Animation CreateAnimation()
        {
            return _proxyGenerator.CreateClassProxy<Animation>(new EventsSourceInterceptor());
        }

        public AnimationStep CreateAnimationStep()
        {
            return _proxyGenerator.CreateClassProxy<AnimationStep>(new[] { new EventsSourceInterceptor() });
        }

        public AnimationStep CloneAnimationStep(AnimationStep animationStep)
        {
            AnimationStep newAnimationStep = CreateAnimationStep();
            newAnimationStep.Percent = animationStep.Percent;

            newAnimationStep.Camera = animationStep.Camera.Clone() as ICamera;

            IList<Molecule> molecules = animationStep.Molecules.Select((m) => 
            {
                return _moleculeFactory.CloneMolecule(m);
            }).ToList<Molecule>();

            newAnimationStep.Molecules = molecules;

            return newAnimationStep;
        }

        public Animation CloneAnimation(Animation animation)
        {
            Animation newAnimation = CreateAnimation();

            newAnimation.AnimationSteps = animation.AnimationSteps.Select((step) =>
                {
                    return CloneAnimationStep(step);
                }).ToList<AnimationStep>();
            newAnimation.Name = animation.Name.Clone() as String;

            return newAnimation;
        }

        #endregion
    }
}
